import React, { Component } from 'react'
import ProType from 'prop-types'


import { Upload, Modal, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { reqDeletePic } from '../../api/index'
import {imgPort} from '../../const_state/port'

function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

export default class PicturesWall extends Component {
    static proType = {
        getImages: ProType.func.isRequired,
        imgs:ProType.array.isRequired
    }
    state = {
        previewVisible: false,
        previewImage: '',
        previewTitle: '',
        fileList: [
            /*    {
                   uid: '-1',
                   name: 'image.png',
                   status: 'done',
                   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
               }, */
        ],
    };

    handleCancel = () => this.setState({ previewVisible: false });

    handlePreview = async file => {
        console.log("这时file", file)
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };
    //上传或者删除图片
    handleChange = async ({ fileList, file }) => {
        console.log("这时filelist", file,file.status)
        //console.log("这时当前的file",file)
        //修改图片中的name，让它和服务器返回的相同，这样后期直接可以访问
        let tempfile = file
        console.log("当前的图片", tempfile)

        // console.log(tempfile.status==='done')
        //不能通过response.status的形式去判断，上传是异步的，可能还没有返回结果
        //通过文件的状态进行判断
        if (tempfile.status === 'done') {
            if (tempfile.response.status === 0) {
                //上传成功
                message.success("上传成功")
                tempfile.name = tempfile.response.data.name
                tempfile.url = tempfile.response.data.url
                //将成功的数据发送给父组件
                console.log("过滤之后的name:", fileList.map((item) => item.name))
                this.props.getImages(fileList.map((item) => item.name))
            } else {
                message.error("网络错误，请稍后")
            }
        }
        else if (tempfile.status === "removed") {
            //发送请求移除图片
            let result = await reqDeletePic(file.name)
            if (result.data.status === 0) {
                message.success("图片移除成功")
                //将成功的数据发送给父组件
                console.log("过滤之后的name:", fileList.map((item) => item.name))
                this.props.getImages(fileList.map((item) => item.name))
            } else {

            }
        }
        else if(tempfile.status==="uploading") {
            
        }
        else{
            message.error("图片上传失败")
        }
        //更新状态
        this.setState({ fileList });
    }
    //如果是修改加载图片
    componentDidMount(){
        if(this.props.imgs[0]){
            let temp = []
            for(let i in this.props.imgs){
                temp.push({
                    uid:-i,
                    name:this.props.imgs[i],
                    status:'done',
                    url:imgPort+this.props.imgs[i]
                })
            }
            this.setState({fileList:temp})
            console.log("我是穿过俩的数组",this.props.imgs,typeof(this.props.imgs))
        }
        // if(this.props.imgs.length){
        //     console.log("HHHHHHHHHHHH",(this.props.imgs.length))
        //  /*    const temp = this.imgs.map((item,index)=>{
        //         return {uid:-index,name:item,status:'done',url:imgPort+item}
        //     })
        //     this.setState({fileList:temp}) */
        // }
    }
    render() {

        const { previewVisible, previewImage, fileList, previewTitle } = this.state;
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div style={{ marginTop: 8 }}>Upload</div>
            </div>
        );
        return (
            <div>
                <Upload
                    accept="image/*" //可以接收的文件类型
                    ///manage/img/upload
                    action="/manage/img/upload" //上传的地址
                    name='image'  //参数的名字
                    listType="picture-card" //文件的样式
                    fileList={fileList} //显示的图片列表
                    onPreview={this.handlePreview} //点击预览图片的回调
                    onChange={this.handleChange} //上传文件改变时的状态
                    onRemove={this.onRemove}
                >
                    {fileList.length >= 3 ? null : uploadButton}
                </Upload>
                <Modal
                    visible={previewVisible}
                    title={previewTitle}
                    footer={null}
                    onCancel={this.handleCancel}
                >
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
}
